
#include "data_global.h"


void release_pthread_resource(int signo);

extern pthread_mutex_t mutex_led,
				mutex_seg,
				mutex_buzzer,
				mutex_fan;

extern pthread_cond_t  cond_led,
				cond_seg, 
				cond_buzzer,
				cond_fan;

extern int msgid;
extern int shmid;
extern int semid;

extern pthread_t id_client_request, //数据下发
		  id_refresh,               //数据上传
		  id_led,
		  id_seg,
		  id_buzzer,
		  id_fan;		

//设备文件描述符
extern int ttyUSB0fd;
extern int buzzerfd;
extern int mpu6050fd;

int main(int argc, const char *argv[])
{

	//打开串口设备文件
	ttyUSB0fd = open_port(ZIGBEE_DEV);
	if(ttyUSB0fd < 0){
		printf("open %s failed\n",ZIGBEE_DEV);
		return ;
	}
	//初始化串口
	if (set_com_config(ttyUSB0fd, 115200, 8, 'N', 1) < 0)
	{
		perror("set_com_config");
		return ;
	}
	//打开蜂鸣器设备文件
	buzzerfd = open(BEEPER_DEV,O_RDWR | O_NONBLOCK);
	if (buzzerfd < 0) {
		perror("open beeper failed.\n");
		return;
	}
	//打开MPU6050设备文件
	mpu6050fd = open(MPU6050_DEV,O_RDWR);
	if (mpu6050fd < 0) {
		perror("open mpu6050 failed.\n");
		return;
	}

	//初始化锁
	pthread_mutex_init(&mutex_led, NULL);
	pthread_mutex_init(&mutex_seg, NULL);
	pthread_mutex_init(&mutex_buzzer, NULL);
	pthread_mutex_init(&mutex_fan, NULL);
	
	//等待接受信号，信号处理函数
	signal (SIGINT, release_pthread_resource);

	//初始化各种条件变量
	pthread_cond_init(&cond_led, NULL);
	pthread_cond_init(&cond_seg, NULL);
	pthread_cond_init(&cond_buzzer, NULL);
	pthread_cond_init(&cond_fan, NULL);

	//创建线程
	pthread_create(&id_client_request, NULL, pthread_client_request, NULL);   
	pthread_create(&id_refresh, NULL, pthread_refresh, NULL);  			
	pthread_create(&id_led, NULL, pthread_led, NULL); 
	pthread_create(&id_seg,	NULL, pthread_seg, NULL);	 
	pthread_create(&id_buzzer, NULL, pthread_buzzer, NULL); 
	pthread_create(&id_fan, NULL, pthread_fan, NULL); 	

	//等待线程退出
	pthread_join(id_client_request, NULL);
	pthread_join(id_refresh, NULL);
	pthread_join(id_led, NULL);
	pthread_join(id_seg, NULL);	
	pthread_join(id_buzzer, NULL);
	pthread_join(id_fan, NULL);

	return 0;
}


void release_pthread_resource(int signo)
{
	//释放锁和条件变量
	pthread_mutex_destroy (&mutex_led);   
	pthread_mutex_destroy (&mutex_seg);   
	pthread_mutex_destroy (&mutex_buzzer);    
	pthread_mutex_destroy (&mutex_fan);     

 	pthread_cond_destroy (&cond_led);
 	pthread_cond_destroy (&cond_seg);
 	pthread_cond_destroy (&cond_buzzer);
 	pthread_cond_destroy (&cond_fan);

	//分离线程的资源
	 pthread_detach(id_client_request);
	 pthread_detach(id_refresh);
	 pthread_detach(id_led);
	 pthread_detach(id_seg);
	 pthread_detach(id_buzzer);
	 pthread_detach(id_fan);

	 printf("all pthread is detached\n");
	 
	 msgctl (msgid, IPC_RMID, NULL);
	 shmctl (shmid, IPC_RMID, NULL);
	 semctl (semid, 1, IPC_RMID, NULL);

	 close(ttyUSB0fd);

	 exit(0);
}



